<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>v-model</title>
</head>

<body>
    <div id="app">
        <form @submit.prevent="handleSubmit">
            <p>姓名：</p>
            <input placeholder="编辑我……" v-model="formData.name" required maxlength="16">

            <p>专业：</p>
            <select v-model="formData.major" required>
                <option value="1">JAVA</option>
                <option value="2">WEB</option>
                <option value="3">UI</option>
            </select>

            <p>性别：</p>
            男：<input type="radio" value="1" name="sex" v-model="formData.sex">
            女：<input type="radio" value="2" name="sex" v-model="formData.sex">

            <p>电话：</p>
            <input placeholder="编辑我……" v-model="formData.tel" required pattern="1\d{10}" maxlength="11">
            <div>
                <button>提交</button>
            </div>
        </form>
        <h2>学生列表</h2>
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>专业</th>
                    <th>电话</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,idx) in arr">
                    <td>{{idx}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.sex == '1' ? '男' : '女'}}</td>
                    <td>{{item.major == '1' ? "JAVA" : item.major == 2 ? 'WEB' : "UI"}}</td>
                    <td>{{item.tel}}</td>
                    <td>
                        <a @click.prevent="handleDelete(idx)">删除</a>
                        <a @click.prevent="handleUpdate(idx)">修改</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
<script src="../../vue.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            formData: {
                sex: "1",
            },
            method: "insert",
            arr: [],
        },
        methods: {
            handleSubmit() {
                // 扩展运算符，浅拷贝
                if (this.method == "insert") {
                    let data = { ...this.formData };
                    this.arr.push(data);
                } else {
                    this.method = "insert";
                }
                this.formData = {
                    sex: "1"
                }
            },
            handleDelete(idx) {
                this.arr.splice(idx,1);
            },
            handleUpdate(idx) {
                this.method = "update";
                this.formData = this.arr[idx];
            }
        }
    })
</script>

</html>